package com.yunji.system.handle;

import com.alibaba.fastjson2.JSON;
import com.yunji.common.base.response.ResponseHelper;
import com.yunji.common.constant.HTTPStatus;
import com.yunji.common.utils.StringUtils;
import com.yunji.common.utils.http.ServletUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serializable;

/**
 * 认证失败处理类 返回未授权
 *
 * @author yunji
 */
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint, Serializable {
    private static final long serialVersionUID = -8970718410437077606L;
    private static final Logger log = LoggerFactory.getLogger(AuthenticationEntryPointImpl.class);

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException {
        int code = HTTPStatus.UNAUTHORIZED;
        String msg = StringUtils.format("请求访问：{}，认证失败，无法访问系统资源", request.getRequestURI());
        log.error("AuthenticationEntryPointImpl commence:{}", msg);
        ServletUtils.renderString(response, JSON.toJSONString(ResponseHelper.failure(code, msg)));
    }
}
